package com.ufm.security.support;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.MessageSourceAccessor;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.SpringSecurityMessageSource;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ufm.security.pojo.Roles;
import com.ufm.security.service.IRolesService;
import com.ufm.syslog.pojo.Syslog;
import com.ufm.syslog.service.ISyslogService;
import com.ufm.user.pojo.User;
import com.ufm.user.service.IUserService;
@Service(value="myUserDetailService")
public class MyUserDetailService implements UserDetailsService {
	@Autowired
	private IUserService userService;
	@Autowired
	private IRolesService rolesService;
	@Autowired
	private ISyslogService syslogService;
	@Autowired
	private HttpServletRequest request;
	
	protected MessageSourceAccessor messages = SpringSecurityMessageSource.getAccessor();

	@Transactional
	@Override
	public UserDetails loadUserByUsername(String username)
            throws UsernameNotFoundException, DataAccessException {
		//1.根据username查找user对象
		User user = userService.findByName(username);
		//2.根据userId查找用户角色
		List<Roles> roles = rolesService.findByUserId(Integer.parseInt(user.getUserId()+""));
		//3.循环遍历添加用户角色
		Collection<GrantedAuthority> auths=new ArrayList<GrantedAuthority>();
		for (Iterator iterator = roles.iterator(); iterator.hasNext();) {
			Roles roles2 = (Roles) iterator.next();
			SimpleGrantedAuthority auth=new SimpleGrantedAuthority("ROLE_"+roles2.getRole_name());
			auths.add(auth);
		}
        org.springframework.security.core.userdetails.User spring_user = new org.springframework.security.core.userdetails.User(username,user.getUserPwd(), true, true, true, true, auths);
        Syslog syslog = new Syslog("登录", "登录", 1, user.getUserId(), user.getUserName(), request.getRemoteAddr(), new Date());
		syslogService.insert(syslog);
        return spring_user;
    }
	
}
